{extend name="user/layout" /}

{block name="title"}编辑个人资料{/block}

{block name="main"}
<main role="main" class="d-flex flex-grow-1">
    <div class="d-flex main-wrap justify-content-between min-vh-100">
        <!-- 中间内容列 -->
        <div class="primary-col">
            <!-- 顶部导航条 -->
            <div class="breadcrumb d-flex align-items-center px-3 js-scroll">
                <div class="btn btn-sm btn-icon me-3 js-back" aria-label="返回" role="button" tabindex="0">
                    <i class="iconfont icon-left-arrow fs-5"></i>
                </div>
                <h2 class="flex-fill fs-18px fw-bold cursor-pointer js-top">
                    <span class="text-truncate">{$user.username}</span>
                </h2>
            </div>

            <!-- 用户信息 -->
            {include file="user/_user_cover"}

            <nav class="nav nav-justified border-bottom">
                <a class="nav-link" id="my-info" href="/user/edit/{$user.id}">账号信息</a>
                <a class="nav-link active" id="my-password" href="/user/password/{$user.id}">更改密码</a>
                <a class="nav-link" id="my-avatar" href="/user/avatar/{$user.id}">设置头像</a>
            </nav>

            <div class="auth-box mx-auto p-4">
                <form id="auth-form" class="needs-validation" method="POST" autocomplete="off">
                    <input type="hidden" name="csrf_token" value="<?= csrf_token() ?>">
                    <div class="form-floating mb-3">
                        <input type="password" class="form-control" name="oldPassword" id="oldPassword" placeholder="旧密码" autocomplete="off" required autofocus>
                        <label for="oldPassword" id="oldPasswordHelp">旧密码</label>
                    </div>
                    <div class="form-floating mb-3">
                        <input type="password" class="form-control" name="newPassword1" id="newPassword1" placeholder="新密码" required>
                        <label for="newPassword1" id="newPassword1Help">新密码</label>
                    </div>
                    <div class="form-floating mb-3">
                        <input type="password" class="form-control" name="newPassword2" id="newPassword2" placeholder="重复新密码" required>
                        <label for="newPassword2" id="newPassword2Help">重复新密码</label>
                    </div>
                    <button type="button" id="changePasswordBtn" class="btn btn-primary p-3 w-100">修改密码</button>
                    <!-- <button type="submit" class="btn btn-secondary w-100 auth-btn px-0">修改密码</button> -->
                </form>
            </div>
        </div>
    </div>
</main>
{/block}

{block name="js"}
<script>
document.addEventListener("DOMContentLoaded", () => {
    // 当前链接添加 active
    highlightActiveLink("user");

    const submitBtn = $('#changePasswordBtn');
    const form = $('#auth-form');
    const oldPasswordInput = $('#oldPassword');
    const newPassword1Input = $('#newPassword1');
    const newPassword2Input = $('#newPassword2');

    const validatePassword = (input, helpText, minLength = 6) => {
        const value = input.val().trim();
        if (value.length < minLength) {
            input.addClass('is-invalid');
            helpText.text(`密码至少 ${minLength} 位数`).addClass('red');
            return false;
        } else {
            input.removeClass('is-invalid');
            helpText.text(input.attr('placeholder')).removeClass('red');
            return true;
        }
    };

    const validatePasswordsMatch = (password1, password2, helpText) => {
        if (password1 !== password2) {
            newPassword2Input.addClass('is-invalid');
            helpText.text('两次输入的密码不一致').addClass('red');
            return false;
        } else {
            newPassword2Input.removeClass('is-invalid');
            helpText.text('重复新密码').removeClass('red');
            return true;
        }
    };

    oldPasswordInput.change(() => {
        flagoldPassword = validatePassword(oldPasswordInput, $('#oldPasswordHelp'));
    });

    newPassword1Input.change(() => {
        flagnewPassword1 = validatePassword(newPassword1Input, $('#newPassword1Help'));
    });

    newPassword2Input.change(() => {
        flagnewPassword2 = validatePassword(newPassword2Input, $('#newPassword2Help'));
        if (flagnewPassword2) {
            flagnewPassword2 = validatePasswordsMatch(newPassword1Input.val().trim(), newPassword2Input.val().trim(), $('#newPassword2Help'));
        }
    });

    submitBtn.click(() => {
        const isOldPasswordValid = validatePassword(oldPasswordInput, $('#oldPasswordHelp'));
        const isNewPassword1Valid = validatePassword(newPassword1Input, $('#newPassword1Help'));
        const isNewPassword2Valid = validatePassword(newPassword2Input, $('#newPassword2Help')) &&
                                    validatePasswordsMatch(newPassword1Input.val().trim(), newPassword2Input.val().trim(), $('#newPassword2Help'));

        if (!isOldPasswordValid || !isNewPassword1Valid || !isNewPassword2Valid) {
            return;
        }

        const data = new FormData(form[0]);

        submitBtn.prop('disabled', true);

        $.ajax({
            method: 'POST',
            url: '/auth/password',
            data: data,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(res) {
                submitBtn.prop('disabled', false);
                if (res.status === 'success') {
                    toast.success(res.message);
                    setTimeout(() => { window.location.reload(); }, 2000);
                } else {
                    toast.error(res.message);
                }
            },
            error: function(xhr) {
                submitBtn.prop('disabled', false);
                toast.error('发生错误，请稍后再试。');
                // console.error(xhr); // 在控制台中记录错误以供调试
            }
        });
    });
});
</script>
{/block}